package com.ny.dao.impl;

import com.ny.dao.ProductDao;
import com.ny.entity.Product;
import com.ny.until.DbUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ProductDaoImpl implements ProductDao {
    private DbUtil dbUtil = new DbUtil();

    @Override
    public List<Product> selectAllProducts() throws SQLException {
        Connection connection = dbUtil.getCon();
        String sql = "SELECT * FROM products";
        PreparedStatement prepareStatement = connection.prepareStatement(sql);
        ResultSet resultSet = prepareStatement.executeQuery();

        List<Product> products = new ArrayList<>();
        while (resultSet.next()) {
            Product product = new Product();
            product.setProductId(resultSet.getInt("product_id"));
            product.setName(resultSet.getString("name"));
            product.setPrice(resultSet.getDouble("price"));
            product.setStock(resultSet.getInt("stock"));
            product.setDescription(resultSet.getString("description"));
            products.add(product);
        }
        return products;
    }
    public Product selectProductById(int productId) throws SQLException {
        Connection connection = dbUtil.getCon();
        String sql = "SELECT * FROM products WHERE product_id = ?";
        PreparedStatement prepareStatement = connection.prepareStatement(sql);
        prepareStatement.setInt(1, productId);
        ResultSet resultSet = prepareStatement.executeQuery();

        if (resultSet.next()) {
            Product product = new Product();
            product.setProductId(resultSet.getInt("product_id"));
            product.setName(resultSet.getString("name"));
            product.setPrice(resultSet.getDouble("price"));
            product.setStock(resultSet.getInt("stock"));
            product.setDescription(resultSet.getString("description"));
            return product;
        }
        return null;
    }

    @Override
    public int updateProductStock(int productId, int quantity) throws SQLException {
        Connection connection = dbUtil.getCon();
        String sql = "UPDATE products SET stock = stock - ? WHERE product_id = ?";
        PreparedStatement prepareStatement = connection.prepareStatement(sql);
        prepareStatement.setInt(2, productId);
        prepareStatement.setInt(1, quantity);
        return prepareStatement.executeUpdate();
    }

    @Override
    public AdminDaoImpl selectAllProduct() {
        return null;
    }
}